<template>
  <!-- 质量整改通知单的操作页，包括：填报 0 ，调整 1 ，查看 2 -->
  <base-breadcrumb :title="$route.meta.title">
    <a-spin :spinning="loading">
      <a-card :bordered="false" class="base-info-style">
          <!-- 基本信息 -->
          <BaseInfo ref="BaseInfo" :form="form" :onlyRead="onlyRead" :orgTreeDisabled="false" />
          <!-- 风险上报信息 -->
          <RiskReportingInfo ref="RiskReportingInfo" :form="form" :onlyRead="onlyRead" @updateForm="updateForm" />
          <!-- 风险复核信息 -->
          <RiskReviewInfo :form="form" :onlyRead="onlyRead" v-if="form.last && form.comStatus != '1'" />
      </a-card>
      <Footer
        :editModel="editModel"
        :loading="footerLoading"
        @submitDraft="submitDraft" 
        @submitFormal="submitFormal" 
      />
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { riskReporting } from '@/api/quality/risk/riskReporting'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/views/quality/riskIdentification/components/BaseInfo'
import RiskReportingInfo from '@/views/quality/riskIdentification/components/RiskReportingInfo'
import RiskReviewInfo from '@/views/quality/riskIdentification/components/RiskReviewInfo'
import Footer from '@/views/quality/riskIdentification/components/Footer'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    RiskReportingInfo,
    RiskReviewInfo,
    Footer
  },
  data() {
    return {
      id: this.$route.query.id || '',
      loading: false, // 请求加载框
      editModel: this.$route.query.editModel || '0', // 操作类型：0 填报，1 调整，2 查看
      form: {
        projectId:"",
        updateUserName: this.$userInfo().name,
        fillTime: this.$dateFormat(Date.now(), 'D'),
      },
      footerLoading: { 'submitDraft': false, 'submitFormal': false, 'submitValidate': false },
      api: riskReporting, // 请求api
      projectId: this.$route.query.projectId || '',
      branchComName: this.$route.query.branchComName || '',
      projectName: this.$route.query.projectName || '',
    }
  },
  created() {
    this.$route.meta.title = [
      '质量风险上报新增',
      '质量风险上报编辑',
      '质量风险上报查看',
    ][this.editModel]
    // 初始化
    this.init()
  },
  computed: {
    // 只读模式
    onlyRead() {
      return this.editModel == 2
    }
  },
  methods: {
    /**
     * @description: 初始化
     */
    init() {
      // 当操作为新增和生成整改单,则自动获取下发人和下发时间，否则请求业务详情
      if (this.id) {
        this.loading = true
        this.api
          .getDetail(this.id)
          .then((res) => {
            if (res.data) {
              // 映射表单
              res.data.projectTypeId = res.data.projectTypeId ? res.data.projectTypeId.toString(): ''
              res.data.subProjectId = res.data.subProjectId ? res.data.subProjectId.toString(): ''
              this.form = res.data
              // 若是编辑，则把下发人和下发时间替换
              if (res.data.branchComName && res.data.projectName) {
                this.form.viewName = res.data.branchComName + '/' + res.data.projectName
              }
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.form.fillerName = this.$userInfo()?.name
        this.form.fillerId = this.$userInfo().id
        this.form.modifiedTime = this.$dateFormat(new Date(), 'D')
        this.form.viewName = this.branchComName + '/' + this.projectName
        this.form.projectId = this.projectId
      }
    },
    submitDraft() {
      try {
          const RiskReportingInfo = this.$refs.RiskReportingInfo
          const dataSource = RiskReportingInfo.dataSource || []
          this.form.losses = dataSource.map(item => {
          const json = {
            typeId: item.id,
            supplementDescription: item.supplementDescription || '',
          }
          return json
        })
        this.submit('submitDraft')
      } catch (e) {
        console.log(e)
      }
    },
    submitFormal() {
      try {
        const BaseInfo = this.$refs.BaseInfo
        BaseInfo.$refs?.ruleForm.validate(valid1 => {
        if (valid1) {
            const RiskReportingInfo = this.$refs.RiskReportingInfo
            RiskReportingInfo.$refs?.ruleForm.validate(valid2=> {
            if (valid2) {
              const columns1 = RiskReportingInfo.columns || []
              // const columns = columns1.filter(v => v.dataIndex === 'supplementDescription').map(item => item.dataIndex)
              const dataSource = RiskReportingInfo.dataSource || []
              if (dataSource.length === 0) {
                this.$warning({
                  title: '提示',
                  content: '风险损失不能为空！',
                  okText: '确定'
                })
                return false
              }
              // const emtyArr = dataSource.filter((obj) => {
              //   let tag = false
              //   for (let key in obj) {
              //     if (columns.indexOf(key) !== -1 && !obj[key]) {
              //       tag = true
              //       break;
              //     }
              //   }
              //   return tag;
              // })
              // if (emtyArr.length) {
              //   this.$warning({
              //     title: '提示',
              //     content: '请将风险损失填写完整再提交！',
              //     okText: '确定'
              //   })
              //   return false
              // }
              this.$confirm({
                titile: '提示',
                content: '确认提交，提交后不可撤回？',
                onOk: () => {
                  this.form.losses = dataSource.map(item => {
                    const json = {
                      typeId: item.id,
                      supplementDescription: item.supplementDescription || '',
                    }
                    return json
                  })
                  return this.submit('submitFormal')
                }
              })
            }
          })
        }
      })
      } catch (e) {
        console.log(e)
      }
    },
    /**
     * @description: 提交表单
     * @param {*} status
     * @return {*}
     */
     submit(status) {
      let name = this.id ? 'updatePost' : 'handleCreate' // 根据操作切换url地址
      // 提交表单
      this.footerLoading[status] = true
      const statusCode = {submitDraft: 0, submitFormal: 1}[status]
      let form = this.$clone(this.form)
      form.status = statusCode
      return this.api[name](form)
        .then((res) => {
          if (res.code === 200 || res.data.code === 200) {
            this.$message.success(['保存草稿', '提交'][statusCode] + '成功！')
            this.$multiTab.close()
          }
        })
        .finally(() => {
          this.footerLoading[status] = false
        })
    },
    updateForm(e) {
      if (e) {
        this.form = Object.assign({}, this.form, e)
      }
    }
  }
}
</script>